// 全局图表实例
let ringChart, mapChart, barChart, rightBarChart;

// DOM加载完成后初始化（避免DOM未加载就执行）
document.addEventListener('DOMContentLoaded', function() {
    const initPeriod = "30"; // 默认加载近30天数据
    // 初始化所有图表和数据
    initRingChart(initPeriod);
    initStoreLineChart(initPeriod); // 折线图替换原表格
    initMapChart(initPeriod);
    initRightTable(initPeriod); // 初始化右侧条形图
    initBarChart(initPeriod);
    updateCoreData(initPeriod);
    updateBottomIndicators(initPeriod);
    bindTimeFilterEvent(); // 绑定时间筛选事件
});

// 时间筛选切换事件
function bindTimeFilterEvent() {
    const timeSpans = document.querySelectorAll('.time-filter span');
    timeSpans.forEach(span => {
        span.addEventListener('click', function() {
            timeSpans.forEach(s => s.classList.remove('active'));
            this.classList.add('active');
            const period = this.getAttribute('data-period');
            // 切换时间周期时更新所有数据和图表
            updateCoreData(period);
            updateStyleRatio(period);
            initRingChart(period);
            initStoreLineChart(period);
            initMapChart(period);
            initRightTable(period); // 更新右侧条形图
            initBarChart(period);
            updateBottomIndicators(period);
        });
    });
}

// 更新顶部核心数据
function updateCoreData(period) {
    const data = dataConfig[period].core;
    document.getElementById('totalPeople').textContent = data.totalPeople;
    document.getElementById('peopleGrowth').textContent = data.peopleGrowth;
    document.getElementById('totalEvents').textContent = data.totalEvents;
    document.getElementById('eventsGrowth').textContent = data.eventsGrowth;
    document.getElementById('totalCoverage').textContent = data.totalCoverage;
    document.getElementById('coverageGrowth').textContent = data.coverageGrowth;
}

// 更新汉服风格占比文字
function updateStyleRatio(period) {
    const ratio = dataConfig[period].styleRatio;
    document.getElementById('styleMing').textContent = ratio.ming + "%";
    document.getElementById('styleTang').textContent = ratio.tang + "%";
    document.getElementById('styleSong').textContent = ratio.song + "%";
    document.getElementById('styleOther').textContent = ratio.other + "%";
}

// 更新底部指标数据
function updateBottomIndicators(period) {
    const data = dataConfig[period].bottom;
    document.getElementById('socialTopic').textContent = data.socialTopic;
    document.getElementById('videoPlay').textContent = data.videoPlay;
    document.getElementById('lectureNum').textContent = data.lectureNum;
    document.getElementById('cooperOrg').textContent = data.cooperOrg;
    document.getElementById('schoolEvent').textContent = data.schoolEvent;
    
    // 添加所有底部指标的点击跳转功能
    setupBottomIndicatorClicks();
}

// 设置所有底部指标的点击跳转功能
function setupBottomIndicatorClicks() {
    const indicators = [
        { selector: '.bottom-indicators .indicator-item:nth-child(1)', url: 'sjmt/hanfu-social-topics.html' },
        { selector: '.bottom-indicators .indicator-item:nth-child(2)', url: 'sjmt/hanfu-video-views.html' },
        { selector: '.bottom-indicators .indicator-item:nth-child(3)', url: 'sjmt/hanfu-lectures.html' },
        { selector: '.bottom-indicators .indicator-item:nth-child(4)', url: 'sjmt/hanfu-cooper-orgs.html' },
        { selector: '.bottom-indicators .indicator-item:nth-child(5)', url: 'sjmt/hanfu-school-events.html' }
    ];
    
    indicators.forEach(indicator => {
        const element = document.querySelector(indicator.selector);
        if (element) {
            // 添加点击样式和动画
            element.style.cursor = 'pointer';
            element.style.transition = 'all 0.3s ease';
            element.style.position = 'relative';
            
            // 添加悬停效果
            element.addEventListener('mouseenter', function() {
                this.style.transform = 'scale(1.05)';
                this.style.boxShadow = '0 0 20px rgba(139, 92, 246, 0.6)';
                this.style.borderColor = '#8B5CF6';
            });
            
            element.addEventListener('mouseleave', function() {
                this.style.transform = 'scale(1)';
                this.style.boxShadow = 'none';
                this.style.borderColor = 'transparent';
            });
            
            // 添加点击事件
            element.addEventListener('click', function() {
                // 添加点击动画
                this.style.transform = 'scale(0.95)';
                setTimeout(() => {
                    this.style.transform = 'scale(1)';
                    // 跳转到对应的大屏
                    window.location.href = indicator.url;
                }, 150);
            });
        }
    });
}

// 环形图（汉服风格占比）
function initRingChart(period) {
    const dom = document.getElementById('ring-chart');
    if (ringChart) ringChart.dispose(); // 销毁旧实例避免冲突
    ringChart = echarts.init(dom);
    const ratio = dataConfig[period].styleRatio;

    const option = {
        backgroundColor: 'transparent',
        tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c}%' },
        series: [{
            name: '汉服风格',
            type: 'pie',
            radius: ['65%', '85%'],
            center: ['50%', '50%'],
            data: [
                { value: ratio.ming, name: '明制', itemStyle: { color: '#d8b4fe' } },
                { value: ratio.tang, name: '唐制', itemStyle: { color: '#b3d1ff' } },
                { value: ratio.song, name: '宋制', itemStyle: { color: '#c8e6c9' } },
                { value: ratio.other, name: '其他', itemStyle: { color: '#ffd700' } }
            ],
            label: {
                color: '#FFFFFF',
                textShadow: '0 0 4px rgba(255,255,255,0.6)'
            }
        }]
    };
    ringChart.setOption(option);
    window.addEventListener('resize', () => ringChart.resize()); // 窗口缩放适配
}

// 体验店数据折线图（替换原表格）
function initStoreLineChart(period) {
    const dom = document.getElementById('store-line-chart');
    if (window.storeLineChart) window.storeLineChart.dispose(); // 销毁旧实例
    window.storeLineChart = echarts.init(dom);
    const storeData = dataConfig[period].storeData;

    // 提取X轴（体验店名称）、Y轴数据（参与人数、活动场次）
    const storeNames = storeData.map(item => item.name);
    const peopleData = storeData.map(item => item.people);
    const eventsData = storeData.map(item => item.events);

    const option = {
        backgroundColor: 'transparent',
        // 添加高级视觉效果
        animation: true,
        animationDuration: 1500,
        animationEasing: 'cubicOut',
        animationDelay: function(idx) { return idx * 50; },
        
        tooltip: {
            trigger: 'axis',
            backgroundColor: 'rgba(10, 10, 30, 0.95)',
            borderColor: '#A66CFF',
            borderWidth: 2,
            borderRadius: 10,
            padding: 15,
            textStyle: { color: '#FFFFFF', fontSize: 14, fontWeight: 'bold' },
            axisPointer: {
                type: 'cross',
                lineStyle: { color: '#A66CFF', width: 2, type: 'dashed' },
                shadowStyle: { color: 'rgba(166, 108, 255, 0.15)' },
                crossStyle: { color: '#A66CFF', width: 1, type: 'dashed' }
            },
            formatter: function(params) {
                let result = `<div style="font-weight: bold; margin-bottom: 8px; color: #A66CFF;">${params[0].name}</div>`;
                params.forEach(param => {
                    const color = param.color;
                    result += `<div style="margin: 5px 0;">
                        <span style="display: inline-block; width: 10px; height: 10px; background: ${color}; border-radius: 50%; margin-right: 6px;"></span>
                        ${param.seriesName}: <span style="color: #FFFFFF; font-weight: bold;">${param.value}</span>
                    </div>`;
                });
                return result;
            }
        },
        
        legend: {
            data: ['参与人数', '活动场次'],
            top: 0,
            textStyle: { 
                color: '#FFFFFF', 
                textShadow: '0 0 8px rgba(166, 108, 255, 1)',
                fontSize: 13,
                fontWeight: 'bold'
            },
            icon: 'roundRect',
            itemWidth: 12,
            itemHeight: 12,
            itemGap: 25,
            borderColor: 'rgba(166, 108, 255, 0.3)',
            borderWidth: 1,
            borderRadius: 6,
            backgroundColor: 'rgba(10, 10, 30, 0.4)',
            padding: [8, 20]
        },
        
        grid: {
            left: '10%',
            right: '8%',
            bottom: '18%',
            top: '25%',
            containLabel: true,
            borderColor: 'rgba(166, 108, 255, 0.1)',
            borderWidth: 1,
            backgroundColor: 'rgba(10, 10, 30, 0.1)'
        },
        
        xAxis: {
            type: 'category',
            data: storeNames,
            axisLine: { 
                lineStyle: { 
                    color: '#A66CFF',
                    width: 2
                } 
            },
            axisLabel: {
                color: '#FFFFFF',
                textShadow: '0 0 6px rgba(166, 108, 255, 1)',
                rotate: 45, // 更大角度旋转避免重叠
                fontSize: 12,
                fontWeight: 'bold'
            },
            axisTick: { 
                lineStyle: { 
                    color: 'rgba(166, 108, 255, 0.5)',
                    width: 2
                },
                alignWithLabel: true
            },
            // 添加分割线增强视觉效果
            splitLine: {
                show: false
            }
        },
        
        yAxis: [
            // 左Y轴：参与人数
            {
                type: 'value',
                name: '参与人数',
                nameTextStyle: { 
                    color: '#00FFCC', 
                    textShadow: '0 0 8px rgba(0, 255, 204, 0.8)',
                    fontSize: 12,
                    fontWeight: 'bold'
                },
                axisLine: { 
                    lineStyle: { 
                        color: '#00FFCC',
                        width: 2
                    } 
                },
                axisLabel: {
                    color: '#FFFFFF',
                    textShadow: '0 0 6px rgba(166, 108, 255, 1)',
                    fontSize: 11,
                    formatter: function(value) {
                        return value >= 1000 ? (value / 1000).toFixed(1) + 'k' : value;
                    }
                },
                splitLine: { 
                    lineStyle: { 
                        color: 'rgba(166, 108, 255, 0.15)',
                        type: 'dashed'
                    }
                },
                axisTick: { 
                    lineStyle: { 
                        color: 'rgba(0, 255, 204, 0.5)',
                        width: 1
                    } 
                }
            },
            // 右Y轴：活动场次（双轴适配不同量级）
            {
                type: 'value',
                name: '活动场次',
                nameTextStyle: { 
                    color: '#FF9EFF', 
                    textShadow: '0 0 8px rgba(255, 158, 255, 0.8)',
                    fontSize: 12,
                    fontWeight: 'bold'
                },
                axisLine: { 
                    lineStyle: { 
                        color: '#FF9EFF',
                        width: 2
                    } 
                },
                axisLabel: {
                    color: '#FFFFFF',
                    textShadow: '0 0 6px rgba(166, 108, 255, 1)',
                    fontSize: 11
                },
                splitLine: { show: false }, // 隐藏右轴网格线避免混乱
                axisTick: { 
                    lineStyle: { 
                        color: 'rgba(255, 158, 255, 0.5)',
                        width: 1
                    } 
                },
                position: 'right'
            }
        ],
        
        series: [
            // 参与人数折线 - 高级版本
            {
                name: '参与人数',
                type: 'line',
                data: peopleData,
                yAxisIndex: 0,
                symbol: 'circle',
                symbolSize: 10,
                smooth: true, // 平滑曲线
                lineStyle: { 
                    color: '#00FFCC', 
                    width: 4,
                    type: 'solid',
                    shadowBlur: 15,
                    shadowColor: 'rgba(0, 255, 204, 0.5)'
                },
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#FFFFFF' },
                        { offset: 1, color: '#00FFCC' }
                    ]),
                    borderColor: '#FFFFFF',
                    borderWidth: 2,
                    shadowBlur: 15,
                    shadowColor: 'rgba(0, 255, 204, 0.7)'
                },
                // 增强区域填充效果
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: 'rgba(0, 255, 204, 0.4)' },
                        { offset: 0.5, color: 'rgba(0, 255, 204, 0.1)' },
                        { offset: 1, color: 'rgba(0, 255, 204, 0)' }
                    ])
                },
                // 标签优化
                label: {
                    show: true,
                    position: 'top',
                    color: '#00FFCC',
                    textShadow: '0 0 8px rgba(0, 255, 204, 1)',
                    fontSize: 11,
                    fontWeight: 'bold',
                    formatter: function(params) {
                        return params.value >= 1000 ? (params.value / 1000).toFixed(1) + 'k' : params.value;
                    }
                },
                // 增加悬浮动画效果
                emphasis: {
                    scale: true,
                    scaleSize: 5,
                    itemStyle: {
                        shadowBlur: 20,
                        shadowColor: 'rgba(0, 255, 204, 0.9)'
                    }
                }
            },
            // 活动场次折线 - 高级版本
            {
                name: '活动场次',
                type: 'line',
                data: eventsData,
                yAxisIndex: 1,
                symbol: 'diamond',
                symbolSize: 10,
                smooth: true, // 平滑曲线
                lineStyle: { 
                    color: '#FF9EFF', 
                    width: 4,
                    type: 'solid',
                    shadowBlur: 15,
                    shadowColor: 'rgba(255, 158, 255, 0.5)'
                },
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#FFFFFF' },
                        { offset: 1, color: '#FF9EFF' }
                    ]),
                    borderColor: '#FFFFFF',
                    borderWidth: 2,
                    shadowBlur: 15,
                    shadowColor: 'rgba(255, 158, 255, 0.7)'
                },
                // 增强区域填充效果
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: 'rgba(255, 158, 255, 0.4)' },
                        { offset: 0.5, color: 'rgba(255, 158, 255, 0.1)' },
                        { offset: 1, color: 'rgba(255, 158, 255, 0)' }
                    ])
                },
                // 标签优化
                label: {
                    show: true,
                    position: 'bottom',
                    color: '#FF9EFF',
                    textShadow: '0 0 8px rgba(255, 158, 255, 1)',
                    fontSize: 11,
                    fontWeight: 'bold'
                },
                // 增加悬浮动画效果
                emphasis: {
                    scale: true,
                    scaleSize: 5,
                    itemStyle: {
                        shadowBlur: 20,
                        shadowColor: 'rgba(255, 158, 255, 0.9)'
                    }
                }
            }
        ]
    };

    window.storeLineChart.setOption(option);
    window.addEventListener('resize', () => window.storeLineChart.resize());
}

// 中国地图（含贵州流向其他省份的流动线条）
function initMapChart(period) {
    const dom = document.getElementById('china-map');
    if (mapChart) mapChart.dispose();
    mapChart = echarts.init(dom);

    // 数据缩放（适配不同时间周期）
    const scale = { 30: 1, 90: 2.2, 365: 4.5 };
    const provinceData = fullProvinceData.map(item => ({
        ...item,
        value: Math.round(item.value * scale[period]),
        isActive: [135, 118, 112, 105, 145].includes(item.value)
    }));
    const maxValue = Math.max(...provinceData.map(item => item.value));

    // 优化的地图颜色方案 - 浅色渐变系列（从浅到深）
    const techColorSeries = [
        '#ffffff', // 最浅的白色背景
        '#f9f0ff', // 极浅粉色
        '#f3e5ff', // 浅粉色
        '#edd3ff', // 中浅粉色
        '#e8c1ff', // 中粉色
        '#dd9dff'  // 较深粉色（但仍然保持浅色范围）
    ];

    // 优化的视觉映射配置（更合理的数据分布区间）
    const getVisualPieces = (max) => {
        // 计算数据分布区间，确保每个区间都有合理的数据展示
        const interval = Math.ceil(max / 6);
        
        return [
            { min: max - interval, label: `${max - interval}+`, color: techColorSeries[5] },
            { min: max - 2 * interval, max: max - interval - 1, label: `${max - 2 * interval}-${max - interval - 1}`, color: techColorSeries[4] },
            { min: max - 3 * interval, max: max - 2 * interval - 1, label: `${max - 3 * interval}-${max - 2 * interval - 1}`, color: techColorSeries[3] },
            { min: max - 4 * interval, max: max - 3 * interval - 1, label: `${max - 4 * interval}-${max - 3 * interval - 1}`, color: techColorSeries[2] },
            { min: max - 5 * interval, max: max - 4 * interval - 1, label: `${max - 5 * interval}-${max - 4 * interval - 1}`, color: techColorSeries[1] },
            { max: max - 5 * interval - 1, label: `<${max - 5 * interval}`, color: techColorSeries[0] }
        ];
    };

    // 贵州流向其他省份的流动线条配置
    const guizhouCoord = [106.71, 26.57]; // 贵州经纬度（中心点）
    const targetProvinces = {
        四川: [104.06, 30.67],
        云南: [102.73, 25.04],
        湖南: [112.98, 28.19],
        广西: [108.33, 22.84],
        重庆: [106.50, 29.53],
        湖北: [114.31, 30.52],
        广东: [113.23, 23.16],
        浙江: [120.19, 30.26],
        江苏: [119.78, 32.04],
        北京: [116.40, 39.90]
    };

    // 构建流动线条数据（从贵州到各目标省份）
    const flowLinesData = Object.values(targetProvinces).map((targetCoord, index) => ({
        coords: [guizhouCoord, targetCoord], // 起点→终点坐标
        lineStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#C8A2FF' }, // 起点：浅紫色（汉服主题）
                { offset: 1, color: '#7F3F98' }  // 终点：深紫色（科技感）
            ])
        },
        z: 3, // 层级高于地图底图
        animationDelay: index * 300 // 线条动画错开延迟，避免同步生硬
    }));

    const rippleThreshold = { 30: 100, 90: 200, 365: 300 }[period];
    const option = {
        backgroundColor: 'transparent',
        animation: true,
        animationDuration: 2000,
        animationEasing: 'cubicInOut',
        animationEasingUpdate: 'quinticInOut',

        tooltip: {
            trigger: 'item',
            backgroundColor: 'rgba(0, 20, 40, 0.9)',
            borderColor: '#3399FF',
            borderWidth: 2,
            borderRadius: 8,
            padding: 15,
            textStyle: { color: '#99CCFF', fontSize: 14 },
            formatter: params => {
                const data = params.data;
                return `
                <div style="font-weight:600;margin-bottom:8px;border-bottom:1px solid #66B2FF;padding-bottom:5px">
                    ${params.name}
                    ${data.isActive ? '<span style="color:#00FFCC;margin-left:5px">★ 核心活跃区</span>' : ''}
                </div>
                <div style="margin:5px 0">活动场次：<span style="color:#FFFFFF">${data.value} 场</span></div>
                <div>同比增长：<span style="color:${data.growth > 10 ? '#00FF99' : '#FFCC66'}">
                    ${data.growth > 0 ? '↑' : ''}${data.growth}%
                </span></div>
            `;
            },
            shadowBlur: 15,
            shadowColor: 'rgba(51, 153, 255, 0.5)'
        },

        visualMap: {
            type: 'piecewise',
            show: true,
            orient: 'horizontal',
            left: 'center',
            bottom: -15, // 下移图例以避免遮挡地图
            itemWidth: 16, // 减小图例项尺寸
            itemHeight: 14,
            pieces: getVisualPieces(maxValue),
            textStyle: {
                color: '#9d4edd',
                textShadow: '0 0 10px rgba(157, 78, 221, 0.8)',
                fontSize: 12,
                fontWeight: 'bold'
            },
            borderColor: '#d946ef',
            borderWidth: 2,
            borderType: 'solid',
            itemGap: 20,
            backgroundColor: 'rgba(253, 244, 255, 0.8)', // 半透明白色背景
            padding: [15, 25],
            borderRadius: 12,
            shadowBlur: 15,
            shadowColor: 'rgba(217, 70, 239, 0.4)',
            // 添加悬停效果
            emphasis: {
                itemStyle: {
                    borderColor: '#a21caf',
                    shadowBlur: 20,
                    shadowColor: 'rgba(162, 28, 175, 0.6)'
                }
            }
        },

        series: [
            // 1. 地图底图
            {
                name: '汉服文化活动',
                type: 'map',
                map: 'china',
                roam: false,
                zoom: 1.2,
                center: [105, 36],
                data: provinceData,
                itemStyle: {
                    normal: {
                        borderColor: '#d8b4fe',  // 浅紫色边框，更清晰可见
                        borderWidth: 1.5, // 稍粗的边框
                        borderType: 'solid', // 实线边框，更清晰
                        shadowBlur: ({data}) => data.isActive ? 6 : 3, // 适度的阴影
                        shadowColor: 'rgba(216, 180, 254, 0.2)',
                        shadowOffsetY: 2,
                        // 保持浅色基调，同时根据数据值调整透明度
                        color: ({value}) => {
                            // 根据值的大小返回不同透明度的颜色，值越大透明度略高
                            const opacity = 0.1 + (value / maxValue) * 0.3; // 透明度范围0.1-0.4
                            return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                { offset: 0, color: `rgba(216, 180, 254, ${opacity * 1.5})` },
                                { offset: 1, color: `rgba(216, 180, 254, ${opacity})` }
                            ]);
                        }
                    },
                    emphasis: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: 'rgba(224, 176, 255, 0.15)' },  // 更浅的强调颜色
                            { offset: 1, color: 'rgba(127, 63, 152, 0.08)' }
                        ]),
                        borderColor: '#E8C3FF',
                        borderWidth: 2,
                        borderType: 'solid',
                        shadowBlur: 12,
                        shadowColor: 'rgba(224, 176, 255, 0.2)',
                        transitionDuration: 800
                    }
                },
                label: {
                    normal: {
                        show: true, // 显示所有省份名称
                        color: '#9d4edd', // 更深的文字颜色，确保清晰可见
                        fontSize: 14, // 增大字号
                        fontWeight: 'bold', // 加粗文字
                        textShadowBlur: 8, // 增加文字阴影
                        textShadowColor: 'rgba(255, 255, 255, 0.9)', // 白色阴影增强对比度
                        formatter: (params) => {
                            // 确保名称完整显示
                            return params.name;
                        }
                    },
                    emphasis: {
                        color: '#7e22ce', // 强调时使用更深的紫色
                        fontSize: 16, // 强调时增大字号
                        fontWeight: 'bold',
                        textShadowBlur: 15,
                        textShadowColor: 'rgba(255, 255, 255, 1)', // 更强的白色阴影
                        fontFamily: 'Arial, sans-serif'
                    }
                },
                z: 1 // 层级最低
            },

            // 2. 贵州流向其他省份的流动线条（核心新增）
            {
                type: 'lines',
                coordinateSystem: 'geo',
                data: flowLinesData,
                polyline: false, // 直线连接
                lineStyle: {
                    width: 6, // 大幅加粗线条，使其更加突出
                    curveness: 0.5, // 更明显的曲线效果
                    type: 'solid', // 实线显示
                    opacity: 1, // 完全不透明
                    color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                        { offset: 0, color: '#FFFFFF' },
                        { offset: 1, color: '#C8A2FF' }
                    ]) // 白紫渐变，增强视觉效果
                },
                // 流动动画配置
                animation: true,
                animationDuration: 2500, // 更快的动画速度
                animationEasing: 'linear',
                animationLoop: true, // 无限循环
                // 线条上的箭头（增强流向感）
                effect: {
                    show: true,
                    symbol: 'arrow',
                    symbolSize: 16, // 更大的箭头
                    color: '#FFFFFF', // 白色箭头，增强对比度
                    trailLength: 0.8, // 更长的拖尾效果
                    constantSpeed: 80, // 更快的移动速度
                    symbolOffset: [0, '50%'], // 调整箭头位置
                    shadowBlur: 10, // 添加阴影效果
                    shadowColor: '#C8A2FF' // 紫色阴影
                },
                z: 2 // 层级介于底图和粒子层之间
            },

            // 3. 粒子特效层（增强科技感）
            {
                type: 'effectScatter',
                coordinateSystem: 'geo',
                data: provinceData.filter(item => item.value > rippleThreshold),
                symbol: 'circle',
                symbolSize: (val) => Math.min(val[2] / (period === '365' ? 80 : 50), 20),
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#C8A2FF' },
                        { offset: 1, color: '#7F3F98' }
                    ]),
                    shadowBlur: 20,
                    shadowColor: 'rgba(166, 108, 255, 0.7)',
                    opacity: 0.9
                },
                rippleEffect: {
                    period: ({data}) => data.isActive ? 2.5 : 4,
                    scale: 4.5,
                    brushType: 'stroke',
                    color: 'rgba(166, 108, 255, 0.5)'
                },
                animation: true,
                animationDuration: 1500,
                animationEasing: 'bounceOut',
                animationDelay: (idx) => idx * 100,
                z: 3 // 层级最高
            }
        ]
    };
    mapChart.setOption(option);
    window.addEventListener('resize', () => mapChart.resize());

    // 鼠标交互效果
    mapChart.on('mousemove', function(params) {
        if (params.data) {
            mapChart.setOption({
                series: [{
                    name: '汉服文化活动',
                    label: {
                        emphasis: {
                            color: '#00FFCC',
                            textShadowBlur: 15
                        }
                    }
                }]
            });
        }
    });
}

// 右侧热门活动条形图
function initRightTable(period) {
    // 获取容器并初始化echarts
    const dom = document.getElementById('right-table');
    // 如果已存在图表实例，先销毁
    if (window.rightBarChart) window.rightBarChart.dispose();
    window.rightBarChart = echarts.init(dom);
    
    // 准备数据
    const eventData = dataConfig[period].eventData;
    const names = eventData.map(item => item.name);
    const peopleData = eventData.map(item => item.people);
    const cities = eventData.map(item => item.city);
    
    // 配置选项
    const option = {
        backgroundColor: 'transparent',
        animation: true,
        animationDuration: 1500,      // 动画持续时间
        animationEasing: 'cubicOut',  // 动画缓动效果
        animationDelay: function(idx) {
            return idx * 100;         // 逐项延迟动画
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow',
                shadowStyle: {
                    color: 'rgba(139, 92, 246, 0.3)'
                }
            },
            backgroundColor: 'rgba(23, 23, 33, 0.9)',
            borderColor: '#8B5CF6',
            borderWidth: 1,
            borderRadius: 8,
            padding: 15,
            textStyle: {
                color: '#FFFFFF'
            },
            formatter: function(params) {
                const index = params[0].dataIndex;
                const data = eventData[index];
                return `
                    <div style="font-weight:600;margin-bottom:8px;border-bottom:1px solid #A66CFF;padding-bottom:5px">
                        ${data.name}
                    </div>
                    <div style="margin:5px 0">排名：<span style="color:#C8A2FF">第${data.rank}名</span></div>
                    <div style="margin:5px 0">城市：<span style="color:#FFFFFF">${data.city}</span></div>
                    <div style="margin:5px 0">参与人数：<span style="color:#FFFFFF">${data.people}</span></div>
                    <div>传播量：<span style="color:#FFFFFF">${data.spread}</span></div>
                `;
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'value',
            axisLine: {
                lineStyle: {
                    color: '#7F3F98'
                }
            },
            axisLabel: {
                color: '#FFFFFF',
                textShadow: '0 0 6px rgba(166, 108, 255, 1.5)',
                fontWeight: 'bold',
                fontSize: 13,
                formatter: function(value) {
                    // 格式化大数字显示
                    if (value >= 10000) {
                        return (value / 10000).toFixed(1) + '万';
                    }
                    return value;
                }
            },
            splitLine: {
                lineStyle: {
                    color: 'rgba(166, 108, 255, 0.1)'
                }
            }
        },
        yAxis: {
            type: 'category',
            data: names,
            axisLine: {
                lineStyle: {
                    color: '#7F3F98'
                }
            },
            axisLabel: {
                color: '#FFFFFF',
                textShadow: '0 0 6px rgba(166, 108, 255, 1.5)',
                fontWeight: 'bold',
                fontSize: 13,
                interval: 0,
                formatter: function(value) {
                    // 截断过长的活动名称
                    return value.length > 10 ? value.substring(0, 10) + '...' : value;
                }
            }
        },
        series: [{
            name: '参与人数',
            type: 'bar',
            data: peopleData,
            itemStyle: {
                color: function(params) {
                    // 高级现代渐变配色方案
                    const gradientColors = [
                        // 紫金渐变
                        new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                            { offset: 0, color: '#D8B4FE' },  // 浅紫色
                            { offset: 0.7, color: '#7E22CE' },  // 深紫色
                            { offset: 1, color: '#4C1D95' }   // 暗紫色
                        ]),
                        // 蓝紫渐变
                        new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                            { offset: 0, color: '#A78BFA' },  // 淡紫色
                            { offset: 0.7, color: '#6D28D9' },  // 中紫色
                            { offset: 1, color: '#5B21B6' }   // 深紫色
                        ]),
                        // 粉紫渐变
                        new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                            { offset: 0, color: '#C084FC' },  // 亮粉色
                            { offset: 0.7, color: '#8B5CF6' },  // 紫色
                            { offset: 1, color: '#6D28D9' }   // 深紫色
                        ]),
                        // 靛紫渐变
                        new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                            { offset: 0, color: '#A5B4FC' },  // 淡蓝色
                            { offset: 0.7, color: '#7C3AED' },  // 靛蓝色
                            { offset: 1, color: '#6B21A8' }   // 深靛色
                        ]),
                        // 玫紫渐变
                        new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                            { offset: 0, color: '#E9D5FF' },  // 淡玫瑰色
                            { offset: 0.7, color: '#9333EA' },  // 紫色
                            { offset: 1, color: '#7E22CE' }   // 深紫色
                        ])
                    ];
                    return gradientColors[params.dataIndex % gradientColors.length];
                },
                borderRadius: [0, 12, 12, 0],  // 更圆润的边角
                shadowBlur: 20,                // 柔和扩散的阴影
                shadowColor: 'rgba(139, 92, 246, 0.6)',  // 更自然的阴影色
                shadowOffsetX: 0,              // 居中阴影效果
                shadowOffsetY: 8,
                borderWidth: 2,                // 增强边框
                borderColor: 'rgba(255, 255, 255, 0.4)'  // 更通透的边框色
            },
            barWidth: '60%',
            label: {
                show: true,
                position: 'right',
                distance: 15,           // 距离柱形图的距离
                color: function(params) {
                    // 根据柱子颜色动态匹配标签颜色
                    const baseColor = params.color.colorStops[0].color;
                    return baseColor;
                },
                textShadow: '0 2px 4px rgba(0, 0, 0, 0.3)',
                fontWeight: 'bold',
                fontSize: 14,
                fontFamily: '"PingFang SC", "Helvetica Neue", Arial, sans-serif',
                formatter: function(params) {
                    const value = params.value;
                    let formattedValue = value;
                    if (value >= 10000) {
                        formattedValue = (value / 10000).toFixed(1) + '万';
                    } else if (value >= 1000) {
                        formattedValue = (value / 1000).toFixed(1) + 'k';
                    }
                    // 添加千分位分隔符（如果需要）
                    return formattedValue.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
                },
                // 标签动画
                showAnimation: 'elasticOut',
                hideAnimation: 'zoom',
                animationDuration: 800
            },
            // 增强悬浮效果
            emphasis: {
                itemStyle: {
                    color: function(params) {
                        // 悬浮时使用更华丽的高亮渐变
                        const highlightGradients = [
                            new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                                { offset: 0, color: '#F3E8FF' },
                                { offset: 0.7, color: '#A855F7' },
                                { offset: 1, color: '#7E22CE' }
                            ]),
                            new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                                { offset: 0, color: '#F5F3FF' },
                                { offset: 0.7, color: '#8B5CF6' },
                                { offset: 1, color: '#6D28D9' }
                            ]),
                            new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                                { offset: 0, color: '#FDF4FF' },
                                { offset: 0.7, color: '#A21CAF' },
                                { offset: 1, color: '#7E22CE' }
                            ]),
                            new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                                { offset: 0, color: '#EFF6FF' },
                                { offset: 0.7, color: '#7C3AED' },
                                { offset: 1, color: '#6B21A8' }
                            ]),
                            new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                                { offset: 0, color: '#FAF5FF' },
                                { offset: 0.7, color: '#9333EA' },
                                { offset: 1, color: '#7E22CE' }
                            ])
                        ];
                        return highlightGradients[params.dataIndex % highlightGradients.length];
                    },
                    shadowBlur: 30,          // 增强悬浮时的阴影
                    shadowColor: 'rgba(139, 92, 246, 0.8)',
                    shadowOffsetY: 10,
                    borderWidth: 2,          // 增强边框
                    borderColor: 'rgba(255, 255, 255, 0.8)'
                },
                scale: true,              // 启用缩放效果
                scaleSize: 5,             // 缩放大小
                focus: 'series',          // 聚焦当前系列
                blurScope: 'series'       // 模糊其他系列
            }
        }]
    };
    
    // 设置选项并添加响应式处理
    window.rightBarChart.setOption(option);
    window.addEventListener('resize', () => window.rightBarChart.resize());
}

// 柱状图（年龄分布）
function initBarChart(period) {
    const dom = document.getElementById('bar-chart');
    if (barChart) barChart.dispose();
    barChart = echarts.init(dom);

    const option = {
        backgroundColor: 'transparent',
        grid: { left: '10%', right: '5%', bottom: '15%', top: '5%' },
        xAxis: {
            type: 'category',
            data: ['18岁以下', '18-25岁', '26-35岁', '36-45岁', '45岁以上'],
            axisLine: { lineStyle: { color: '#4A90E2' } },
            axisLabel: { color: '#FFFFFF', textShadow: '0 0 4px rgba(255,255,255,0.6)' }
        },
        yAxis: {
            type: 'value',
            name: '占比(%)',
            nameTextStyle: { color: '#5BC0DE', textShadow: '0 0 6px rgba(91,202,222,0.6)' },
            axisLine: { lineStyle: { color: '#4A90E2' } },
            axisLabel: { color: '#4A90E2', textShadow: '0 0 4px rgba(255,255,255,0.6)' }
        },
        series: [{
            type: 'bar',
            data: dataConfig[period].ageData,
            itemStyle: { color: '#BA68C8' },
            barWidth: 30,
            label: { show: true, color: '#FFFFFF', textShadow: '0 0 4px rgba(255,255,255,0.6)' }
        }]
    };
    barChart.setOption(option);
    window.addEventListener('resize', () => barChart.resize());
}